<template>
  <div class="app-container">
    <div v-show="!modifyInfo.visible && !modifyInfoPrint.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-export>
            <el-button :disabled="!canExport" @click="onBatchPrintQRcode()">
              打印选择RFID码
            </el-button>
          </template>
          <template v-slot:filter-remove>
            <el-button :disabled="!canRemove" @click="remove">删除</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <select id="selected_device" style="width: 0; opacity: 0"></select>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
      </table-container>
    </div>

    <scrap-export-order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :export-id="modifyInfo.exportId"
      :action="modifyInfo.action"
      :baseData="modifyInfo.baseData"
      @returnModify="returnModify"
    />
    <modifyPrint
      v-if="modifyInfoPrint.visible"
      v-model:visible="modifyInfoPrint.visible"
      :title="modifyInfoPrint.title"
      :export-id="modifyInfoPrint.exportId"
      :action="modifyInfoPrint.action"
      :baseData="modifyInfoPrint.baseData"
      @returnModify="returnModify"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <AddBydeliverOrder
      v-if="addDeliverDialog.visible"
      v-model:visible="addDeliverDialog.visible"
      @callback="addDeliverBack"
    />
    <AddStorageOrder
      v-if="addStorageOrderInfo.visible"
      v-model:show-dialog="addStorageOrderInfo.visible"
      v-model:query="addStorageOrderInfo.query"
      :check-box="false"
      :highlight-row="true"
      @callback="addStorageOrderCallback"
    />
    <ChosePrinter
      v-model:visible="printerInfo.visible"
      @callBack="handlePrinterCallBack"
    />
    <!-- 修改弹窗 -->
    <PageDialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title[dialogInfo.type]"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <!-- form -->
      <PageForm
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      />
    </PageDialog>
  </div>
</template>

<script setup name="smartCabinetTagBinding">
import TableContainer from '@/components/TableContainer/index'
import AddBydeliverOrder from './addBydeliverOrder'
import AddStorageOrder from './addStorageOrder'
import {
  getRfidBindCustomizeListPage,
  removeRfidBind,
  removeRfidBindMore,
  updateRfidBind,
  pushRfidBindInfo,
  rfidBindPrint,
} from '@/api/smartCabinet'
import ScrapExportOrderModify from './modify'
import modifyPrint from './modifyPrint'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const printerInfo = ref({
  visible: false,
  data: {},
})
const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/index')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)
const addDeliverDialog = ref({
  visible: false,
})
// 弹窗相关
const dialogInfo = ref({
  title: {
    create: '添加',
    update: '修改',
  },
  visible: false,
  type: '',
  width: '40%',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: save,
      saveLoading: false,
      show: true,
    },
  ],
})
// 表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '产品编码', value: 'code', type: 'input', disabled: true },
    {
      label: '产品名称',
      value: 'commonName',
      type: 'input',
      disabled: true,
    },
    {
      label: '规格',
      value: 'standard',
      type: 'input',
      disabled: true,
    },
    {
      label: '厂家',
      value: 'supplierName',
      type: 'input',
      disabled: true,
    },
    {
      label: '个体码',
      value: 'uniqueCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '原RFID码',
      value: 'rfidCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '新RFID码',
      value: '_rfidCode',
      type: 'input',
      required: true,
    },
  ],
  rules: {
    _rfidCode: { required: true, message: '请输入新RFID码', trigger: 'blur' },
  },
  labelWidth: '100px',
})
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    customizeUserVO: {},
    queryMap: {
      depotAuth: {
        asTbName: 'smart_cabinet_rfid_bind',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('smartCabinetTagBinding:add'),
    },
    {
      type: 'button',
      label: '新增并打印',
      event: createPrint,
      disabled: !proxy.$store.state.permission.systemConfig.force_print_in_rfid,
      show: proxy.$permission('smartCabinetTagBinding:add'),
    },
    {
      type: 'slot',
      label: '删除',
      value: 'remove',
      show: proxy.$permission('smartCabinetList:delete'),
    },
    /* {
      type: 'button',
      label: '根据发货单绑定',
      event: modifyByDeliver,
      show: proxy.$permission('smartCabinetTagBinding:modifyByDeliver'),
    },
    {
      type: 'button',
      label: '根据入库单绑定',
      //event: receivingImport,
      event: addStorageProduct,
      show: proxy.$permission('smartCabinetTagBinding:addStorageProduct'),
    }, */

    {
      type: 'slot',
      value: 'export',
      show: proxy.$permission('scrapExportOrder:export'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('smartCabinetTagBinding:update'),
        ifRender: function (row) {
          return row.pushStatus === 0
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('smartCabinetTagBinding:delete'),
        ifRender: function (row) {
          return row.pushStatus === 0
        },
      },
      {
        label: '推送',
        event: submit,
        popconfirmText: '是否确认推送数据？',
        show: proxy.$permission('smartCabinetTagBinding:submit'),
        ifRender: function (row) {
          return row.pushStatus === 0
        },
      },
    ],
  },
})
const modifyInfo = reactive({
  action: 'add',
  visible: false,
  exportId: '',
  title: '',
})
const modifyInfoPrint = reactive({
  action: 'add',
  visible: false,
  exportId: '',
  title: '',
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
const addStorageOrderInfo = ref({
  visible: false,
  query: {
    status: 3,
    depotId: '',
    deptId: '',
  },
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const selected_device = ref('')
const time = ref([])
const isNotUsbDevices = ref('')
const canRemove = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.pushStatus !== 0).length
  )
})
const canExport = computed(() => {
  return (
    tableInfo.selections.length &&
    proxy.$store.state.permission.systemConfig.force_print_in_rfid
    // && !tableInfo.selections.filter((item) => item.pushStatus !== 3).length
  )
})

onMounted(() => {
  var devices = []
  BrowserPrint.getDefaultDevice(
    'printer',
    function (device) {
      //Add device to list of devices and to html select element
      selected_device.value = device
      devices.push(device)
      var html_select = document.getElementById('selected_device')
      var option = document.createElement('option')
      option.text = device.name
      html_select.add(option)
      //Discover any other devices available to the application
      BrowserPrint.getLocalDevices(
        function (device_list) {
          if (device_list && device_list.length == 1 && !device_list[0].name) {
            isNotUsbDevices.value = true
          } else {
            isNotUsbDevices.value = false
          }
          for (var i = 0; i < device_list.length; i++) {
            //Add device to list of devices and to html select element
            var device = device_list[i]
            if (
              !selected_device.value ||
              device.uid != selected_device.value.uid
            ) {
              devices.push(device)
              var option = document.createElement('option')
              option.text = device.name
              option.value = device.uid
              html_select.add(option)
            }
          }
        },
        function () {
          console('Error getting local devices')
        },
        'printer'
      )
    },
    function (error) {
      console.log(error)
    }
  )
})

let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'scrap_export_order_status',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function finishedCallback() {}

function errorCallback() {}
//入库单绑定
function addStorageProduct() {
  addStorageOrderInfo.value.visible = true
}
function onBatchPrintQRcode() {
  if (tableInfo.selections.length) {
    if (isNotUsbDevices.value) {
      proxy.$message({
        message: '打印机未正常连接',
        type: 'warning',
      })
      return
    }
    rfidBindPrint(tableInfo.selections).then((res) => {
      if (res && res.success) {
        let data = res.data
        selected_device.value.send(data, finishedCallback, errorCallback)
      }
    })
  } else {
    proxy.$message({
      message: '选择需要打印的RFID码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
  }
}
function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
function addStorageOrderCallback(data) {
  proxy.$nextTick(() => {
    if (data && data.id) {
      addStorageOrderInfo.value.visible = false
      modifyInfo.exportId = ''
      modifyInfo.title = '根据入库单绑定'
      modifyInfo.action = 'addStorageOrder'
      modifyInfo.baseData = data
      modifyInfo.visible = true
    }
  })
}
//发货单绑定
function modifyByDeliver() {
  addDeliverDialog.value.visible = true
}
//发货单绑定返回
function addDeliverBack(data) {
  proxy.$nextTick(() => {
    if (data && data.id) {
      addDeliverDialog.value.visible = false
      modifyInfo.exportId = ''
      modifyInfo.title = '根据发货单绑定'
      modifyInfo.action = 'addBydeliverOrder'
      modifyInfo.baseData = data
      modifyInfo.visible = true
    }
  })
}
function returnModify() {
  if (modifyInfo.exportId) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'smart_cabinet_rfid_bind',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
function close() {
  dialogInfo.value.visible = false
  formInfo.value.data = {}
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(formInfo.value.data))
      let api = updateRfidBind
      dialogInfo.value.btLoading = true
      params.rfidCode = params._rfidCode
      api([params])
        .then((res) => {
          if (res.success) {
            dialogInfo.value.visible = false
            getList()
          }
          dialogInfo.value.btLoading = false
        })
        .catch(() => {
          dialogInfo.value.btLoading = false
        })
    }
  })
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
//删除
function remove(row) {
  if (row && row.id) {
    removeRfidBind(row.id).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    proxy
      .$confirm('删除后将改变数据，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        let ids = getIds(row)
        removeRfidBindMore(ids).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
        })
      })
  }
}
//创建
function create() {
  modifyInfo.exportId = ''
  modifyInfo.title = '新增标签绑定'
  modifyInfo.action = 'add'
  modifyInfo.visible = true
}
function createPrint() {
  modifyInfoPrint.exportId = ''
  modifyInfoPrint.title = '新增并打印'
  modifyInfoPrint.action = 'add'
  modifyInfoPrint.visible = true
}
function update(row) {
  dialogInfo.value.visible = true
  if (row.codeType == 3) {
    formInfo.value.fieldList.forEach((element) => {
      if (element.value === 'uniqueCode') {
        element.label = '原厂从码'
        element.value = 'factorySubCode'
      }
    })
  }
  if (row.codeType == 2) {
    formInfo.value.fieldList.forEach((element) => {
      if (element.value === 'factorySubCode') {
        element.label = '个体码'
        element.value = 'uniqueCode'
      }
    })
  }
  // 显示信息
  formInfo.value.data = { ...row }
}
//提交
function submit(row = undefined) {
  pushRfidBindInfo(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function getIds(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((row) => row.id)
  }
  return ids
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'smartCabinetRfidBind-com.slip.spd.entity.vo.smartCabinet.SmartCabinetRfidBindVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      console.log(tableInfo.fieldList)
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getRfidBindCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
